package com.baor.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.Equipment_abnormalityDao;
import com.baor.domain.*;
import com.baor.service.ExceptiongdService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//设备工单
@Service
@Slf4j
public class ExceptiongdServiceImpl implements ExceptiongdService {
    @Autowired
    private Equipment_abnormalityDao EquipmentReportDao;

    @Override
    public R getList(Map<String, Object> params) {
        Page page = new Page();
        page.setCurrent((Integer) params.get("pageIndex"));
        page.setSize((Integer) params.get("pageSize"));
        MPJLambdaWrapper<Equipment_abnormality> wrapper = new MPJLambdaWrapper<>(Equipment_abnormality.class)
                .select(Equipment_abnormality::getId,
                        Equipment_abnormality::getGdId,
                        Equipment_abnormality::getAbnormalType,
                        Equipment_abnormality::getAbnormalDescription,
                        Equipment_abnormality::getReportUserId,
                        Equipment_abnormality::getReportTime,
                        Equipment_abnormality::getHandlerId,
                        Equipment_abnormality::getHandleTime,
                        Equipment_abnormality::getHandleStatus,
                        Equipment_abnormality::getMaterial,
                        Equipment_abnormality::getResult
                        )
                .select(Equipment::getCode,
                        Equipment::getAddress)
                .selectAs("handler.username", ExceptiongdVO::getHandlerUsername)
                .selectAs("report.username", ExceptiongdVO::getReportUsername)
                .leftJoin(UserVO.class, "handler", UserVO::getId, Equipment_abnormality::getHandlerId)
                .leftJoin(UserVO.class, "report", UserVO::getId, Equipment_abnormality::getReportUserId)
                .leftJoin(Equipment.class, Equipment::getId, Equipment_abnormality::getEquipmentId)
                .orderByDesc(Equipment_abnormality::getReportTime);

        String code = (String) params.get("code");
        String abnormalType = (String) params.get("abnormalType");
        Integer handleStatus = (Integer) params.get("handleStatus");
        String address = (String) params.get("address");
        // 添加设备编号
        if (StringUtils.hasText(code)) {
            wrapper.like(Equipment::getCode, code);
        }
        if(StringUtils.hasText(address)){
            wrapper.like(Equipment::getAddress, address);
        }
        // 添加异常类型
        if (StringUtils.hasText(abnormalType)) {
            wrapper.like(Equipment_abnormality::getAbnormalType, abnormalType);
        }
        // 添加处理状态
        if (handleStatus != null) {
            wrapper.eq(Equipment_abnormality::getHandleStatus, handleStatus);
        }
        Page<ExceptiongdVO> Page = this.EquipmentReportDao.selectJoinPage(page, ExceptiongdVO.class, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("totalSize", Page.getTotal());
        map.put("List", Page.getRecords());
        if (Page.getTotal() == 0){
            return R.er("未查询到工单信息");
        }else{
            return R.ok(map);
        }
    }

    /**
     * 添加设备异常工单
     * @param params
     * @return
     */
    @Override
    @Transactional
    public R insert(Map<String, Object> params) {
            Equipment_abnormality equipmentReport = new Equipment_abnormality();

            // 生成工单号：XQ+年月日时分
            String workOrderNo = generateWorkOrderNo();
            equipmentReport.setGdId(workOrderNo);

            // 设置异常类型和异常描述
            if (params.containsKey("abnormalType")) {
                equipmentReport.setAbnormalType(params.get("abnormalType").toString());
            } else {
                return R.er("异常类型不能为空");
            }

            if (params.containsKey("abnormalDescription")) {
                equipmentReport.setAbnormalDescription(params.get("abnormalDescription").toString());
            } else {
                return R.er("异常描述不能为空");
            }

            // 设置上报用户ID
            if (params.containsKey("reportUserId")) {
                equipmentReport.setReportUserId(Integer.valueOf(params.get("reportUserId").toString()));

            } else {
                return R.er("上报用户不能为空");
            }
            // 设置设备ID
            if (params.containsKey("equipmentId")) {
                equipmentReport.setEquipmentId((Integer) params.get("equipmentId"));
            } else {
                return R.er("设备不能为空");
            }

            // 设置上报时间为当前时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            equipmentReport.setReportTime(LocalDateTime.now().format(formatter));

            // 设置创建时间和更新时间
            equipmentReport.setCreatedAt(LocalDateTime.now().format(formatter));
            equipmentReport.setUpdatedAt(LocalDateTime.now().format(formatter));

            // 初始处理状态为未处理（0表示未处理）
            equipmentReport.setHandleStatus(0);

            // 设置审核状态为待审核（根据实际业务调整状态码）
            equipmentReport.setReviewerStatus(0);
            equipmentReport.setReportStatus(1);

            System.out.println("equipmentReport:"+equipmentReport);
            // 使用 MyBatis Plus 保存到数据库
            int result = EquipmentReportDao.insert(equipmentReport);

            System.out.println("result:"+result);
            if (result > 0) {
                return R.ok("工单添加成功");
            } else {
                return R.er("工单添加失败");
            }
    }

    private String generateWorkOrderNo() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
        String dateStr = LocalDateTime.now().format(formatter);
        return "XQ" + dateStr;
    }


    @Override
    public R getInfo(Integer id) {
        log.info("工单详情ID:{}",id);
        MPJLambdaWrapper<Equipment_abnormality> wrapper = new MPJLambdaWrapper<>(Equipment_abnormality.class)
                .eq(Equipment_abnormality::getId, id)
                .select( Equipment_abnormality::getId,
                        Equipment_abnormality::getGdId,
                        Equipment_abnormality::getAbnormalType,
                        Equipment_abnormality::getAbnormalDescription,
                        Equipment_abnormality::getReportUserId,
                        Equipment_abnormality::getReportTime,
                        Equipment_abnormality::getHandlerId,
                        Equipment_abnormality::getHandleTime,
                        Equipment_abnormality::getHandleStatus,Equipment_abnormality::getMaterial,
                        Equipment_abnormality::getResult)
                .select(Equipment::getCode,
                        Equipment::getAddress)
                .selectAs("handler.username", ExceptiongdVO::getHandlerUsername)
                .selectAs("report.username", ExceptiongdVO::getReportUsername)
                .leftJoin(UserVO.class, "handler", UserVO::getId, Equipment_abnormality::getHandlerId)
                .leftJoin(UserVO.class, "report", UserVO::getId, Equipment_abnormality::getReportUserId)
                .leftJoin(Equipment.class, Equipment::getId, Equipment_abnormality::getEquipmentId);
        List<ExceptiongdVO> list = this.EquipmentReportDao.selectJoinList(ExceptiongdVO.class, wrapper);
        if (list.isEmpty()){
            return R.er("未查询到工单信息");
        }else {
            return R.ok(list);
        }
    }

}
